package com.example.goodscontentresolver.utils;

import android.content.ContentResolver;
import android.content.UriMatcher;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class MessageObserver extends ContentObserver {

    private final ContentResolver contentResolver;

    public MessageObserver(ContentResolver contentResolver) {
        super(new Handler(Looper.getMainLooper()));
        this.contentResolver = contentResolver;
    }

    @Override
    public void onChange(boolean selfChange, @Nullable Uri uri) {
        super.onChange(selfChange, uri);
        if (uri == null) {
            return;
        }

        String prefix = "content://sms/raw/";
        String uriString = uri.toString();
        if (uriString.equals(prefix) || uriString.equals("content://sms")) {
            return;
        }

        String smsId = null;

        if (uriString.startsWith(prefix)) {
            smsId = uriString.substring(prefix.length());
        }
        if (smsId == null) {
            return;
        }

        Uri queryUri = Uri.parse("content://sms");

        try (Cursor cursor = contentResolver.query(queryUri, null/*new String[]{"address","body","date"}*/,/*"_id = ?",new String[]{smsId}*/null, null, null)) {
            //注意要求要有短信的读取权限
            if (cursor == null) {
                Log.d("短信监听器", "查询短信失败，也许是没有授权?");
                return;
            }
            while (cursor.moveToNext()) {
                Log.d("收到短信", String.format("%s  %s  %s", cursor.getString(0), cursor.getString(1), cursor.getString(2)));
                // 查询短信的具体信息
            }
        }
    }
}
